package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.TimeUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.businesslibrary.net.pojo.UserInfo;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.eventbus.UserInfoChangeEvent;
import com.blockmeta.bbs.immodule.net.api.DeleteFriendApi;
import com.blockmeta.bbs.immodule.net.api.GetUserInfoApi;
import com.blockmeta.bbs.immodule.net.api.ShieldUserApi;
import com.blockmeta.bbs.immodule.utils.IMUtils;
import com.blockmeta.bbs.immodule.widget.IMAddFriendMsg;
import com.suke.widget.SwitchButton;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouterPath.PERSONHOME,extras = RouterConstant.EXTRAL_LOGIN)
public class PersonHomeActivity extends BaseActivity {

    @Autowired(name = Constant.ZERO)
    public String mUserId;

    @BindView(R2.id.avatar)
    CircleImageView avatar;
    @BindView(R2.id.tv_user_title)
    TextView tvUserTitle;
    @BindView(R2.id.tv_user_name)
    TextView tvUserName;
    @BindView(R2.id.tv_user_boatage_title)
    TextView tvUserBoatageTitle;
    @BindView(R2.id.tv_user_boatage)
    TextView tvUserBoatage;
    @BindView(R2.id.llayout_setting)
    LinearLayout llayoutSetting;
    @BindView(R2.id.llayout_homepage)
    LinearLayout llayoutHomepage;
    @BindView(R2.id.iv_icon_person)
    ImageView ivIconPerson;
    @BindView(R2.id.tv_homepage_title)
    TextView tvHomepageTitle;
    @BindView(R2.id.llayout_card)
    LinearLayout llayoutCard;
    @BindView(R2.id.iv_icon_card)
    ImageView ivIconCard;
    @BindView(R2.id.tv_card_title)
    TextView tvCardTitle;
    @BindView(R2.id.llayout_shield)
    LinearLayout llayoutShield;
    @BindView(R2.id.llayout_remark)
    LinearLayout llayoutRemark;
    @BindView(R2.id.iv_icon_ring)
    ImageView ivIconRing;
    @BindView(R2.id.tv_shield_title)
    TextView tvShieldTitle;
    @BindView(R2.id.sb_shield)
    SwitchButton sbShield;
    @BindView(R2.id.btn_add_friend)
    Button btnAddFriend;
    @BindView(R2.id.btn_delete_friend)
    Button btnDeleteFriend;
    @BindView(R2.id.btn_send_message)
    Button btnSendMessage;


    public UserInfo mUserInfo;

    @Override
    protected boolean showTitle() {
        return true;
    }


    @Override
    public View setView() {
        setTitleText("");
        return getLayoutInflater().inflate(R.layout.activity_homepage, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        IMApplicationContext.getIMMetaService().register(this);

//        mUserId = "33672";
        if ("0".equals(mUserId)) {
            finish();
        }
        netWork();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void netWork() {
        ProgressBarUtil.showProgress(this);
        RetrofitFactory.getRootRetrofit().create(GetUserInfoApi.class)
                .getUserInfo(mUserId)
                .compose(RxUtil.<BaseImResponse<UserInfo>>rxSchedulerHelper())
                .compose(RxUtil.<UserInfo>commonResult())
                .compose(this.<UserInfo>bindToLifecycle())
                .subscribe(new CommonSubscriber<UserInfo>(mContext) {
                    @Override
                    public void onNext(UserInfo userInfo) {
                        //绑定ui数据
                        mUserInfo = userInfo;
                        IMApplicationContext.getUserDomainService().updateUserNameAndAvator(userInfo.getUserId()
                                , userInfo.getUserName(), userInfo.getLogo(), userInfo.getGroupId());

                        bindUserInfo(userInfo);

                    }
                });
    }

    private void bindUserInfo(UserInfo userInfo) {
        if (userInfo != null) {
            tvUserName.setText(TextUtils.isEmpty(userInfo.getRemarkName()) ? userInfo.getUserName() : userInfo.getRemarkName());
            LoadPicUtil.loadWithPicasso(avatar, userInfo.getLogo());
            tvUserTitle.setText(IMUtils.UserLevel.getUserLevel(userInfo.getGroupId()).getValue());
            tvUserBoatage.setText(TimeUtil.getUserRegisterAge(String.valueOf(userInfo.getRegdate())));

            setShieldSwitch(userInfo.isShield());
            boolean isMe = userInfo.getUserId() == AccountHelper.getUidInt();
            boolean hideMyHome = userInfo.getHomePageShow() > 0;
            boolean isFriend = IMApplicationContext.getUserDomainService().isFriend(Integer.parseInt(mUserId));

            if(isMe){
                llayoutHomepage.setVisibility(View.VISIBLE);
                llayoutRemark.setVisibility(View.GONE);
                llayoutShield.setVisibility(View.GONE);
                btnDeleteFriend.setVisibility(View.GONE);
                btnAddFriend.setVisibility(View.GONE);
                btnSendMessage.setVisibility(View.GONE);
            }else{
                if (isFriend) {
                    llayoutShield.setVisibility(View.GONE);
                    llayoutRemark.setVisibility(View.VISIBLE);
                    btnAddFriend.setVisibility(View.GONE);
                    btnDeleteFriend.setVisibility(View.VISIBLE);

                } else {
                    llayoutShield.setVisibility(View.VISIBLE);
                    llayoutRemark.setVisibility(View.GONE);
                    btnAddFriend.setVisibility(View.VISIBLE);
                    btnDeleteFriend.setVisibility(View.GONE);
                }
                llayoutHomepage.setVisibility(hideMyHome ? View.GONE : View.VISIBLE);
            }

        }else {
            ToastUtil.show("用户不存在");
            llayoutHomepage.setVisibility(View.GONE);
        }


    }

    private void setShieldSwitch(boolean isShield) {
        sbShield.setOnCheckedChangeListener(null);
        sbShield.setChecked(isShield);
        sbShield.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                view.setEnabled(false);
                shieldUser(Integer.parseInt(mUserId), isChecked);

            }
        });
    }

    private void shieldUser(final int toId, final boolean isChecked) {
        ProgressBarUtil.showProgress(mContext);
        RetrofitFactory.getRootRetrofit().create(ShieldUserApi.class)
                .shieldUser(toId, isChecked)
                .compose(RxUtil.dataNullResult())
                .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                .compose(((RxAppCompatActivity) mContext).<BaseImResponse<Object>>bindToLifecycle())
                .subscribe(new CommonSubscriber<BaseImResponse<Object>>(mContext) {
                    @Override
                    public void onNext(BaseImResponse<Object> o) {
                       sbShield.setEnabled(true);
                       EventBus.getDefault().post(new IMMetaBase.EventShieldFriend(isChecked));
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        ToastUtil.show("失败");
                        setShieldSwitch(!isChecked);
                        sbShield.setEnabled(true);
                    }
                });
    }

    @OnClick({R2.id.llayout_homepage, R2.id.llayout_card, R2.id.llayout_remark, R2.id.btn_send_message, R2.id.btn_add_friend, R2.id.btn_delete_friend})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.llayout_homepage) {
            RouterHelper.buildPath(RouterPath.WEB_ACTIVITY)
                    .withString(Constant.ZERO, NetConstant.PERSONAL_HOME + mUserId)
                    .withString(Constant.ONE, "个人资料-趣会论坛")
                    .navigation(mContext);
        } else if (id == R.id.llayout_card) {
            Intent personalQRIntent = new Intent(mContext, PersonalQrCodeActivity.class);
            personalQRIntent.putExtra(Params.USERID, Long.parseLong(mUserId));
            personalQRIntent.putExtra(Params.USER_NAME, mUserInfo.getUserName());
            personalQRIntent.putExtra(Params.USER_AVATAR, mUserInfo.getLogo());
            personalQRIntent.putExtra(Params.USER_DESC, mUserInfo.getIndividualResume());
            startActivity(personalQRIntent);
        } else if (id == R.id.llayout_remark) {
            Intent remarkIntent = new Intent(mContext, RemarksActivity.class);
            remarkIntent.putExtra(Params.USERID, Long.parseLong(mUserId));
            startActivity(remarkIntent);
        } else if (id == R.id.btn_send_message) {
            RouterHelper.startActivity(this, RouterPath.IM_UUChatActivity_ACTIVITY, mUserId);

        } else if (id == R.id.btn_add_friend) {
            IMAddFriendMsg imPopAddFriendMsg = new IMAddFriendMsg(mContext, mUserId, null);
            imPopAddFriendMsg.show();
        } else if(id == R.id.btn_delete_friend){
            ProgressBarUtil.showProgress(mContext);
            RetrofitFactory.getRetrofit().create(DeleteFriendApi.class)
                    .deleteFriend(AccountHelper.getUidInt(), Long.parseLong(mUserId))
                    .compose(RxUtil.dataNullResult())
                    .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                    .compose(((RxAppCompatActivity) mContext).<BaseImResponse<Object>>bindToLifecycle())
                    .subscribe(new CommonSubscriber<BaseImResponse<Object>>(mContext) {
                        @Override
                        public void onNext(BaseImResponse<Object> o) {
                            ToastUtil.show("删除好友成功");
                            IMApplicationContext.getUserDomainService().deleteFriend(Integer.parseInt(mUserId));
                            IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_DeleteFriends());
                            btnAddFriend.setVisibility(View.VISIBLE);
                            btnDeleteFriend.setVisibility(View.GONE);
                        }
                    });
        }
    }

    /**
     * 从其他页面修改后通知接收处
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UserInfoChangeEvent msg) {
        if (msg.userId == Long.parseLong(mUserId)) {
            if (msg.changeInfoMap.containsKey("shield")) {
                mUserInfo.setShield(Boolean.parseBoolean(msg.changeInfoMap.get("shield")));
                setShieldSwitch(Boolean.parseBoolean(msg.changeInfoMap.get("shield")));
            }
            if (msg.changeInfoMap.containsKey(Params.REMARK)) {
                String remarkName = msg.changeInfoMap.get(Params.REMARK);
                mUserInfo.setRemarkName(remarkName);
                if(TextUtils.isEmpty(remarkName)){
                    tvUserName.setText(mUserInfo.getUserName());
                }else {
                    tvUserName.setText(mUserInfo.getRemarkName());
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_AddFriends event){
        //添加好友，判断是否是当前用户，需要隐藏上面的陌生人框
        LogUtils.d("author" + "uuchat receive add friend msg");
        relationBarStatusChange();
    }

    private void relationBarStatusChange() {
        bindUserInfo(mUserInfo);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_DeleteFriends event){
        //添加好友，判断是否是当前用户，需要隐藏上面的陌生人框
        LogUtils.d("author" + "uuchat receive remove friend msg");
        relationBarStatusChange();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IMApplicationContext.getIMMetaService().unregister(this);
    }


}
